package com.example.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;

import java.io.IOException;

@WebFilter(filterName = "CharacterEncodeFilter", urlPatterns = "/*",
        initParams = {@WebInitParam(name = "encode", value = "UTF-8")})
public class CharacterEncodeFilter implements Filter {
    private String encode;
    public void init(FilterConfig config) throws ServletException {
        //获取上下文参数
        this.encode = config.getInitParameter("encode");
    }
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //设置请求的字符
        request.setCharacterEncoding(this.encode);
        //设置响应的字符编码
        response.setContentType("text/html;charset=UTF-8");
        chain.doFilter(request, response);
    }
}
